package org.example.steamshop.service;

import org.example.steamshop.model.CartItem;
import org.example.steamshop.model.Game;
import org.example.steamshop.repository.CartItemRepository;
import org.example.steamshop.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class CartService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private CartItemRepository cartItemRepository;

    @Autowired
    private GameService gameService;

    public List<CartItem> getCartItems(Long userId) {
        return cartItemRepository.findByUserId(userId);
    }


    public void addToCart(Long userId, Long gameId) {
        Game game = gameService.findGameById(gameId);
        if (game == null) {
            throw new RuntimeException("Game not found");
        }

        List<CartItem> cartItems = cartItemRepository.findByUserId(userId);
        Optional<CartItem> existingItem = cartItems.stream()
                .filter(item -> item.getGame().getId().equals(gameId))
                .findFirst();

        if (existingItem.isPresent()) {
            CartItem item = existingItem.get();
            item.setQuantity(item.getQuantity() + 1);
            cartItemRepository.save(item);
        } else {
            CartItem newItem = new CartItem();
            newItem.setUser(userRepository.findById(userId).orElse( null));
            newItem.setGame(game);
            newItem.setQuantity(1);
            cartItemRepository.save(newItem);
        }
    }
    public void clearCart(Long userId) {
        cartItemRepository.deleteByUserId(userId);
    }

    public void removeFromCart(Long userId, Long gameId) {
        cartItemRepository.deleteByUserIdAndGameId(userId, gameId);
    }

    public void updateCartItemQuantity(Long userId, Long gameId, int quantity) {
        CartItem cartItem = cartItemRepository.findByUserIdAndGameId(userId, gameId)
                .orElseThrow(() -> new RuntimeException("Cart item not found")); // 直接抛异常

        cartItem.setQuantity(quantity);
        cartItemRepository.save(cartItem);
    }

}